package com.ty.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ty.mybatis.entity.Columns;
import com.ty.mybatis.entity.Tables;
import com.ty.util.PropertiesUtil;

import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * 
 * @ClassName: TestMain 
 * @Description: 自动创建一个项目 包含 pojo mapper service 等
 * @author zzx
 *
 * @date 2020年12月31日
 */
public class TestMain {

	private static PropertiesUtil p = new PropertiesUtil();

	
	public static void main(String[] args) throws Exception {
		test();
	}

	public static void test() throws Exception {
		// 通过FreeMarker的Confuguration读取相应的模板文件
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
//		// 设置模板路径
		String tempPath = ClassLoader.getSystemResource("").toString().replace("file:/", "").replace("%20", " ")
				+ p.getProperty("tempPath");
		configuration.setDirectoryForTemplateLoading(new File(tempPath));
//		// 设置默认字体
		configuration.setDefaultEncoding("utf-8");
//		// 设置模型
		String[] tables = p.getProperty("table").split(",");
		String[] entitys = p.getProperty("entity").split(",");
		String[] srcs = p.getProperty("src").split(",");
//		
		Tables t = getTables(tables[0], entitys[0], srcs[0]);
		
		String path = p.getProperty("path");
		
		// 生成model
		processFile(configuration, t, "model.ftl",
				path + p.getProperty("ModelProject") + "src/main/java/com/ty/model/" + t.getSrc() + "/",
				t.getEntity() + ".java");
		// 生成IDao
		processFile(configuration, t, "IDao.ftl",
				path + p.getProperty("MapperProject") + "src/main/java/com/ty/mapper/" + t.getSrc() + "/",
				"" + t.getEntity() + "Mapper.java");
		// 生成Mapping文件
		processFile(configuration, t, "Mapper.ftl",
				path + p.getProperty("MapperProject") + "src/main/java/com/ty/mapper/" + t.getSrc() + "/",
				t.getEntity() + "Mapper.xml");
		// 生成IService
		processFile(configuration, t, "IService.ftl",
				path + p.getProperty("IServiceProject") + "src/main/java/com/ty/service/" + t.getSrc() + "/",
				"I" + t.getEntity() + "Service.java");
		// 生成serviceImpl
		processFile(
				configuration, t, "ServiceImpl.ftl", path + p.getProperty("ServiceImplProject")
						+ "src/main/java/com/ty/service/" + t.getSrc() + "/impl/",
				t.getEntity() + "ServiceImpl.java");
		System.out.println("*** end *****************");
	}
	
	private static Tables getTables(String table, String entity, String src) throws Exception {
		String url = p.getProperty("jdbc.url");
		String driver = p.getProperty("jdbc.driver");
		String username = p.getProperty("jdbc.username");
		String password = p.getProperty("jdbc.password");
		
		Class.forName(driver).newInstance();
		Connection conn = (Connection) DriverManager.getConnection(url, username, password);
		PreparedStatement pstmt = conn.prepareStatement("select database()");
		ResultSet rs = pstmt.executeQuery();
		String dataBase = null;
		while (rs.next()) {
			dataBase = rs.getString(1);
		}
		rs.close();
		pstmt.close();
		Tables t = null;
		List<String> importList = new ArrayList<String>();
		importList.add("java.io.Serializable");
		if (dataBase != null) {
			t = new Tables();
			t.setTable(table);
			t.setEntity(entity);
			t.setSrc(src);
			List<Columns> pList = new ArrayList<Columns>();
			List<Columns> cList = new ArrayList<Columns>();
			List<Columns> notPriList = new ArrayList<Columns>();
			boolean isSame = true;
			String priType = "";
			pstmt = conn.prepareStatement(
					"select column_name,data_type,column_key from information_schema.columns where table_schema = '"
							+ dataBase + "' and table_name = '" + table + "'");
			rs = pstmt.executeQuery();
			while (rs.next()) {
				Columns c = new Columns(rs.getString(1), rs.getString(2));
				cList.add(c);
				if (rs.getString(3).toUpperCase().equals("PRI")) {
					if(priType.equals(""))
						priType = c.getJavaType();
					if(!priType.equals("") && !priType.equals(c.getJavaType()))
						isSame = false;
					pList.add(c);
				} else
					notPriList.add(c);
				if (!c.getJavaType2().contains("java.lang") && !importList.contains(c.getJavaType2()))
					importList.add(c.getJavaType2());
				if (c.getJavaType().equals("Byte[]") && !importList.contains("java.util.Arrays"))
					importList.add("java.util.Arrays");
			}
			if(pList.size() > 1) {
				t.setPriType(isSame ? priType : "Object");
				t.setPriKeys(pList);
			} else
				t.setPriKey(pList.get(0));
			
			t.setColList(cList);
			t.setNotPriList(notPriList);
			rs.close();
			pstmt.close();
		}
		Collections.sort(importList);
		t.setImportList(importList);
		conn.close();
		return t;
	}
	
	private static void processFile(Configuration configuration, Tables table, String templatePath, String filePath,
			String fileName) {
		FileWriter out = null;
		try {
			// 获取模板
			Template template = configuration.getTemplate(templatePath);
			// 设置输出文件
			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 设置输出流
			out = new FileWriter(new File(filePath + fileName));
			// 模板输出静态文件
			template.process(table, out);

		} catch (TemplateNotFoundException e) {
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
